package com.lv.suyiyong.hfrbusines.ui

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.azhon.appupdate.listener.OnDownloadListener
import com.azhon.appupdate.manager.DownloadManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.ActivityCollector
import com.lv.common.base.BaseActivity
import com.lv.common.base.BaseApplication
import com.lv.common.event.VersionUpdataRefreshEvent
import com.lv.common.imp.OnDialogListener
import com.lv.common.network.model.DataResult
import com.lv.common.service.UpdataAppService
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.MyUtils
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.service.dialog.FirstDialog
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.address.AddressDbHelper
import com.lv.service.room.card.CardAddressDbHelper
import com.lv.service.room.card.CardCategoryDbHelper
import com.lv.service.room.card.CardColorDbHelper
import com.lv.service.room.category.CategoryDbHelper
import com.lv.service.room.category.NewTelCategoryCityDbHelper
import com.lv.service.room.category.NewTelCategoryDbHelper
import com.lv.service.room.category.SpuCategoryDbHelper
import com.lv.service.room.saler.SalerDbHelper
import com.lv.service.room.saler.SuerDbHelper
import com.lv.suyiyong.hfrbusines.R
import com.lv.suyiyong.hfrbusines.YgxApplication
import com.lv.suyiyong.hfrbusines.bean.TokenBean
import com.lv.suyiyong.hfrbusines.bean.VersionUpdate
import com.lv.suyiyong.hfrbusines.databinding.ActivitySplashBinding
import com.lv.suyiyong.hfrbusines.dialog.VersionUpdateDialog
import com.lv.suyiyong.hfrbusines.moudel.MainViewModel
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.io.File
import kotlin.system.exitProcess

@Route(path = ARoutUtils.SplashActivity)
class SplashActivity : BaseActivity<ActivitySplashBinding>() {
    private var isLogin = false
    private lateinit var downUrl: String
    private val REQUEST_CODE_APP_INSTALL = 110
    private var upDataDialog: VersionUpdateDialog? = null
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val viewModel: MainViewModel by viewModel()
    override fun getLayoutRes() = R.layout.activity_splash
    override fun initView() {
        super.initView()
        SalerDbHelper.deleteAllSaler(this@SplashActivity)
        SuerDbHelper.deleteAllSaler(this@SplashActivity)
        CategoryDbHelper.deleteAllCategory(this@SplashActivity)
        CardCategoryDbHelper.deleteAllCategory(this@SplashActivity)
        AddressDbHelper.deleteAllAddress(this@SplashActivity)
        SpuCategoryDbHelper.deleteAllCategory(this@SplashActivity)
        CardAddressDbHelper.deleteAllAddress(this@SplashActivity)
        CardColorDbHelper.deleteAllCardColor(this@SplashActivity)
        NewTelCategoryDbHelper.deleteAllCategory(this@SplashActivity)
        NewTelCategoryCityDbHelper.deleteAllCategory(this@SplashActivity)

//        initStatusBar(this, true, true)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 后台返回时可能启动这个页面 http://blog.csdn.net/jianiuqi/article/details/54091181
        if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
            finish()
            return
        }
        val isOpend = SPStaticUtils.getBoolean(Constants.ISOPEND, false)//是否打开过App

        if (!isOpend) {
            val chatToken = SPStaticUtils.getString(Constants.KEY_CHAT_TOKEN, "aaa")
            if ("aaa" == chatToken) {
                val randomString: String = MyUtils.getRandomString(16)
                SPStaticUtils.put(Constants.KEY_CHAT_TOKEN, randomString)
            }
            val firstDialog: FirstDialog = FirstDialog(this)
            firstDialog.setCanceledOnTouchOutside(false)
            firstDialog.show()
            firstDialog.setLeftBtnClickListener {
                firstDialog.dismiss()
                ActivityUtils.finishAllActivities()
            }
            firstDialog.setRightBtnClickListener {
                SPStaticUtils.put(Constants.ISOPEND, true)
                firstDialog.dismiss()
                findVersionUpdate()
            }

        } else {
            findVersionUpdate()
        }

    }

    private fun findVersionUpdate() {
        viewModel.findVersionUpdate()
    }

    override fun initConfig() {
        super.initConfig()

        viewModel.apply {
            //版本更新结果
            versionUpDateLiveData.observeKt {
                it?.let {
                    val versionListBean = it[0]
                    val isprivacy = versionListBean.isprivacy//是否显示隐私弹窗
                    val fristLoadVersion = SPStaticUtils.getString(Constants.ISFRISTLOADVERSION, "")
                    if (!fristLoadVersion.isNullOrEmpty() && fristLoadVersion != isprivacy) {
                        val firstDialog: FirstDialog = FirstDialog(this@SplashActivity)
                        firstDialog.setCanceledOnTouchOutside(false)
                        firstDialog.show()
                        firstDialog.setLeftBtnClickListener {
                            firstDialog.dismiss()
                            ActivityUtils.finishAllActivities()
                        }
                        firstDialog.setRightBtnClickListener {
                            SPStaticUtils.put(Constants.ISFRISTLOADVERSION, isprivacy ?: "")
                            firstDialog.dismiss()
                            checkUpDataVersion(versionListBean)
                        }
                    } else {
                        SPStaticUtils.put(Constants.ISFRISTLOADVERSION, isprivacy ?: "")
                        checkUpDataVersion(versionListBean)
                    }

                }
            }

        }
    }

    //检查更新弹窗
    private fun checkUpDataVersion(versionListBean: VersionUpdate) {
        val versionID = versionListBean.jump
        val status = versionListBean.iscompel ?: "0" //1 一直显示
//        val versionID = "2.5.0"
//        val status = "1"
        downUrl = versionListBean.url
        val compareVersion =
            MyUtils.compareVersion(
                BaseApplication._versionName,
                versionID
            )//0代表相等，1代表systemVersion大于android_version_num，-1代表systemVersion小于android_version_num
        if (compareVersion == -1) {//版本更新 // 版本号不同 当前版本大于强制更新版本，不升级，小于，升级
            upDataDialog =
                VersionUpdateDialog(
                    this@SplashActivity,
                    versionListBean, false, false, object : OnDialogListener {
                        override fun onSureClick(content: String?) {
                            val appName = AppUtils.getAppVersionName()
                            val manager = DownloadManager.Builder(this@SplashActivity).run {
                                apkUrl(downUrl)
                                apkName("suyiyiong_O.apk")
                                smallIcon(R.drawable.ic_launcher)
                                //设置了此参数，那么内部会自动判断是否需要显示更新对话框，否则需要自己判断是否需要更新
//                                apkVersionCode(2)
                                //同时下面三个参数也必须要设置
                                apkVersionName(appName)
//                                apkSize("7.7MB")
//                                apkDescription("更新描述信息(取服务端返回数据)")
                                onDownloadListener(object : OnDownloadListener {
                                    override fun cancel() {
                                    }

                                    override fun done(apk: File) {
                                        val hint = "下载完成"
                                        mHint?.text = hint

                                        if (packageManager.canRequestPackageInstalls()) {
                                            if (!downUrl.isNullOrEmpty()) {
                                                updataLoading()
                                                val intent =
                                                    Intent(
                                                        this@SplashActivity,
                                                        UpdataAppService::class.java
                                                    )
                                                intent.putExtra("url", downUrl)
                                                startService(intent)
                                                return
                                            }
                                        } else {
                                            upDataDialog?.show()
                                        }
                                    }

                                    override fun downloading(max: Int, progress: Int) {
//                                        val progress = event.progress
                                        if (mLoadingDialog?.isShowing == false) {
                                            mLoadingDialog?.show()
                                        }
                                        val process = ((progress.toFloat() / max) * 100).toInt()
                                        val hint = "下载进度:${process}%"
                                        mHint?.text = hint
                                    }

                                    override fun error(e: Throwable) {
                                    }

                                    override fun start() {
                                        updataLoading()
                                    }
                                })
                                //省略一些非必须参数...
                                build()

                            }
                            manager.download()
//                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !packageManager.canRequestPackageInstalls()) {
//                                //开启设置安装未知来源应用权限界面
//                                val packageURI =
//                                    Uri.parse("package:$packageName")
//                                val intent = Intent(
//                                    Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
//                                    packageURI
//                                )
//                                startActivityForResult(intent, REQUEST_CODE_APP_INSTALL)
//                            } else {
//                                updataLoading()
//                                val intent = Intent(
//                                    this@SplashActivity,
//                                    UpdataAppService::class.java
//                                )
//                                intent.putExtra("url", downUrl)
//                                startService(intent)
//                            }


                        }

                        override fun onCancelClick() {
                            if (status == "1") {
                                ActivityCollector.finishAll()
                            } else {
                                upDataDialog?.dismiss()
                                checkToken()
                            }
                            //                                        registerCutAndCopyEvents()
                        }
                    })
            upDataDialog?.show()
        } else {
            checkToken()
        }
    }

    private fun checkToken() {
        lifecycleScope.launchWhenCreated {
            this.launch {
                val result: DataResult<BaseYgxRsp> =
                    myScope.async { viewModel.refreshtoken() }.await()
                parseTokenResult(result)
            }
        }

    }

    private fun parseTokenResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<TokenBean> { code, data, message, result ->
                if (data != null && !TextUtils.isEmpty(data.token)) {
                    YgxUtilsKt.setAppToken(data.token, data.refreshtoken)
                    lifecycleScope.launch {
                        val userInfo = UserDbHelper.getUserSuspendInfo(this@SplashActivity)
                        if (userInfo?.id != null) {
                            login(userInfo)
                        } else {
                            logOut()
                        }
                    }

                } else {
                    logOut()
                }
            }
            onBizError<Any> { code, message, data ->
//                showToast(message)
                logOut()

            }
        }
        data.onFailure {
//            showToast("refreshtoken 接口异常")
            ActivityUtils.finishAllActivities()
        }
    }

    private fun login(userInfo: UserInfo) {
        TUILogin.login(
            this,
            YgxApplication.getInstance().getSdkAppId(),
            userInfo.txaccid,
            userInfo.txaccidpassword,
            object :
                TUICallback() {
                override fun onSuccess() {
                    isLogin = true
//                    showToast("登录成功 ")
                    startMain()
                    YgxApplication.getInstance().registerPushManually()
//                    TIMAppService.getInstance().registerPushManually()
                    YgxUtilsKt.sendMessgeToSelf(userInfo.txaccid, userInfo.phone)
                }

                override fun onError(errorCode: Int, errorMessage: String?) {
                    showToast("登录失败 $errorCode,errorInfo = $errorMessage")
                    startLogin()
                    LogUtils.e("imLogin errorCode = $errorCode, errorInfo = $errorMessage")
                }
            })
    }

    private fun startMain() {
        startLoading()
        lifecycleScope.launchWhenCreated {
            this.launch {
                val result: DataResult<BaseYgxRsp> =
                    myScope.async { serviceViewModel.latestUser() }.await()
                parseLaterUserResult(result)
            }
        }

    }

    private fun parseLaterUserResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                data?.let {
                    UserDbHelper.UpDataUserInfo(this@SplashActivity, data)
                    startActivity(Intent(this@SplashActivity, HomeActivity::class.java))
                    overridePendingTransition(
                        com.lv.common.R.anim.screen_zoom_in,
                        com.lv.common.R.anim.screen_zoom_out
                    )
                    finish()
                }
            }
            onBizError<Any> { code, message, data ->
                if (code == "201") {
                    logOut()
                }
                showToast(message)
            }
        }
        data.onFailure {
            LogUtils.e("eee")
        }
    }

    private fun logOut() {
        TUILogin.logout(object : TUICallback() {
            override fun onSuccess() {
                V2TIMManager.getConversationManager()
                    .removeConversationListener(null)
            }

            override fun onError(errorCode: Int, errorMessage: String?) {
            }
        })
        //清除Token
        YgxUtilsKt.setAppToken("", "", "")
        startLogin()
        finish()
    }


    private fun startLogin() {
        UserDbHelper.deleteUserInfo(this@SplashActivity)
        val isExist = MyUtils.isExistActivity(this, LoginActivity::class.java)
        if (!isExist) {
            ARouter.getInstance().build(ARoutUtils.LoginActivityURL).navigation()
        }
    }

    override fun initEvents() {
        super.initEvents()
        rigestEventBus()
    }

    private fun rigestEventBus() {
        LiveEventBus.get(VersionUpdataRefreshEvent::class.java).observe(this) { event ->
            if (event == null) {
                return@observe
            }
            val progress = event.progress
            if (mLoadingDialog?.isShowing == false) {
                mLoadingDialog?.show()
            }
            var hint = ""
            if (progress == 100) {
                hint = "下载完成"
            } else {
                hint = "下载进度:${progress}%"
            }
            mHint?.text = hint
        }
    }

    private var mLoadingDialog: Dialog? = null
    private var mHint: TextView? = null
    private fun updataLoading() {
        // 创建一个进度条对话框
        mLoadingDialog = Dialog(this)
        val contentView: View = LayoutInflater.from(this)
            .inflate(R.layout.updata_loading, null)
        mHint = contentView.findViewById<TextView>(R.id.tv_text)
        mLoadingDialog?.setContentView(contentView)

//        val layoutParams: ViewGroup.LayoutParams = contentView.layoutParams
//        layoutParams.width = resources.displayMetrics.widthPixels
//        contentView.layoutParams = layoutParams
        mLoadingDialog?.window?.setGravity(Gravity.CENTER)
        mLoadingDialog?.setCanceledOnTouchOutside(false)

        mLoadingDialog?.show()


    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
//        if (data == null) {
//            return
//        }
        when (requestCode) {
            REQUEST_CODE_APP_INSTALL -> {
                if (packageManager.canRequestPackageInstalls()) {
                    if (!downUrl.isNullOrEmpty()) {
                        updataLoading()
                        val intent =
                            Intent(
                                this@SplashActivity,
                                UpdataAppService::class.java
                            )
                        intent.putExtra("url", downUrl)
                        startService(intent)
                    }
                } else {
                    showToast("暂无安装应用权限")
                    upDataDialog?.show()
                }

            }
//            else -> {
//                if (data != null) {
//                    //QQ回调
//                    ShareUtils.get().onQqActivityResult(requestCode, resultCode, data)
//                }
//            }
        }
    }

    private var exitTime: Long = 0
    override fun onBackPressed() {
        super.onBackPressed()
        exitProcess(0)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun exit() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            showToast("再按一次退出程序")
            exitTime = System.currentTimeMillis()
        } else {
            YgxApplication.getInstance().exit()
            finish()
        }
    }
}